<template>
  <el-dialog
    :title="showTitle"
    :visible="dialogVisible"
    @close="closeDialog"
    @open="openDialog"
  >
    <el-form ref="deptForm" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <div slot="footer">
      <el-button type="primary" size="small" @click="submit">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { reqGetEmployeeSimple } from '@/api/employees'
import { reqAddDepartments, reqGetDepartDetail, reqUpdateDepartments } from '@/api/departments'
export default {
  props: {
    // 弹层显示
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 节点数据
    nodeData: {
      type: Object,
      required: true
    },
    depts: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义校验规则 value表示输入的值 callback回调函数
    // 必须用箭头函数，因为this指向问题
    const validateName = (rule, value, callback) => {
      // console.log(value, this.nodeData)
      // callback()
      /* 简单版 第二套 校验部门名称在整个模块中不允许重复---------------------------------------- */
      // 编辑部门名称校验-简单版
      // if (this.form.id) {
      //   if (this.nodeData.name === value) { return callback() }
      // }
      // const isRepeat = this.depts.some(item => item.name === value)
      // isRepeat ? callback(new Error(`已经有了${value}部门名称`)) : callback()
      /* 复杂版 第一套------------------校验同级部门中禁止出现重复部门*/
      let children = []
      if (this.form.id) {
        if (this.nodeData.name === value) { return callback() }
        children = this.depts.filter(item => item.pid === this.nodeData.pid)
      } else {
        children = this.depts.filter(item => item.pid === this.nodeData.id)
      }
      const isRepeat = children.some(item => item.name === value)
      isRepeat ? callback(new Error(`同级部门下已经有了${value}名称了`)) : callback()
    }
    const validateCode = (rule, value, callback) => {
      // console.log(value, this.depts)
      // 数据双向绑定 不能用this.form.code  和value的值一样
      // console.log(this.nodeData.code, value)
      if (this.form.id) {
        if (this.nodeData.code === value) { return callback() }
      }
      const isRepeat = this.depts.some(item => item.code === value)
      isRepeat ? callback(new Error(`已经有了${value}部门编码`)) : callback()
    }
    return {
      options: [],
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: ['change', 'blur'] },
          { min: 1, max: 50, message: '必填1到50个字符', trigger: ['change', 'blur'] },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: ['change', 'blur'] },
          { min: 1, max: 50, message: '必填1到50个字符', trigger: ['change', 'blur'] },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: ['change', 'blur'] }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: ['change', 'blur'] },
          { min: 1, max: 300, message: '必填1到300个字符', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  // 计算属性动态控制标题 方法里面要return
  computed: {
    showTitle() {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  async created() {
    // 单独抽离个方法，打开弹框的时候在调用接口
    // const { data } = await reqGetEmployeeSimple()
    // console.log(data)
    // 赋值
    // this.options = data
    this.getEmployeeSimple()
  },
  methods: {
    async getDepartDetail(id) {
      const { data } = await reqGetDepartDetail(id)
      console.log(data)
      this.form = data
    },
    closeDialog() {
      this.$emit('update:dialogVisible', false)
      // form实例方法，重置表单
      this.$refs.deptForm.resetFields()
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    openDialog() {
      // this.getEmployeeSimple()
    },
    async getEmployeeSimple() {
      const { data } = await reqGetEmployeeSimple()
      // console.log(data)
      // 赋值
      this.options = data
    },
    async submit() {
      // 方法一
      // try {
      //   await this.$refs.deptForm.validate()
      //   console.log('校验成功')
      // } catch (error) {
      //   console.log('校验失败')
      // }
      // 方法2
      // this.$refs.deptForm.validate((flag) => {
      //   if (flag) {
      //     console.log('校验成功')
      //   } else {
      //     console.log('校验失败')
      //   }
      // })
      // 方法三
      this.$refs.deptForm.validate().then(async() => {
        console.log('校验通过')
        /*
        封装新增保存接口并调用
        提示成功信息
        刷新列表
        关闭请求
        */
        // 区分是编辑还是新增 看id
        if (!this.form.id) {
          await reqAddDepartments({ ...this.form, pid: this.nodeData.id })
          // this.$message.success('新增部门成功')
        } else {
          await reqUpdateDepartments(this.form)
          // this.$message.success('编辑部门成功')
        }
        // 提示信息简写
        this.$message.success(this.showTitle + '成功')
        this.$emit('add-depts')
        this.closeDialog()
      }).catch(() => {
        console.log('校验失败')
      })
    }
  }
}
</script>

<style>

</style>
